using System;
using Cysharp.Threading.Tasks;
using EarthUtility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using System.Linq;
using System.Collections.Generic;

namespace Cesium3DTilesSelection
{
    public class IonRasterOverlay : RasterOverlay
    {

        private int _ionAssetID;
        private string _ionAccessToken;
        public IonRasterOverlay(string name, int ionAssetID, string ionAccessToken)
        {
            this._ionAssetID = ionAssetID;
            this._ionAccessToken = ionAccessToken;
        }
        public override async UniTask<RasterOverlayTileProvider> createTileProvider(IPrepareRendererResources pPrepareRendererResources, RasterOverlay pOwner)
        {
            string ionUrl = "https://api.cesium.com/v1/assets/" + this._ionAssetID + "/endpoint";
            ionUrl = ionUrl + "?access_token=" + _ionAccessToken;
            pOwner = pOwner ?? this;
            string jsonConfig = await http.Get(ionUrl);
            var response = JObject.Parse(jsonConfig);
            string type = response.TryGetValue("type", out JToken value) ? ((string)value) : "unknown";
            if (type != "IMAGERY")
            {
                Debug.Log($"Ion raster overlay metadata response type is not 'IMAGERY', but {{type}}");
            }

            string externalType = JsonHelpers.getStringOrDefault(response, "externalType", "unknown");
            if (externalType == "BING")
            {
                var options = response["options"];
                if (options.HasValues || options.Type != JTokenType.Object)
                {
                    Debug.LogError("Cesium ion Bing Maps raster overlay metadata response does not contain 'options' or it is not an object.");
                    return null;
                }

                string bingurl = JsonHelpers.getStringOrDefault(options, "url", "");
                string key = JsonHelpers.getStringOrDefault(options, "key", "");
                string mapStyle = JsonHelpers.getStringOrDefault(options, "mapStyle", "AERIAL");
                string culture = JsonHelpers.getStringOrDefault(options, "culture", "");

                return await new BingMapsRasterOverlay(this.name, bingurl, key, mapStyle, culture).createTileProvider(pPrepareRendererResources, pOwner);
            }
            string url = JsonHelpers.getStringOrDefault(response, "url", "");
            Dictionary<string, string> header = new Dictionary<string, string> { { "Authorization", "Bearer " + JsonHelpers.getStringOrDefault(response, "accessToken", "") } };
            return await new TileMapServiceRasterOverlay(this.name, url, header).createTileProvider(pPrepareRendererResources, pOwner);
        }
    }

}